package icu.groot.alan.hotel.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.gson.Gson;
import icu.groot.alan.hotel.entity.dao.AdminDo;
import icu.groot.alan.hotel.entity.dao.HotelDo;
import icu.groot.alan.hotel.entity.dao.OrderDo;
import icu.groot.alan.hotel.entity.dao.RoomDo;
import icu.groot.alan.hotel.entity.dto.AdminUpdatePasswordRo;
import icu.groot.alan.hotel.entity.dto.LoginAdminDto;
import icu.groot.alan.hotel.entity.req.AdminLoginRo;
import icu.groot.alan.hotel.entity.req.AdminOrderRo;
import icu.groot.alan.hotel.entity.vo.AdminOrderVo;
import icu.groot.alan.hotel.entity.vo.LoginAdminVo;
import icu.groot.alan.hotel.entity.vo.OrderListVo;
import icu.groot.alan.hotel.entity.vo.RoomVo;
import icu.groot.alan.hotel.enums.OrderStatusEnum;
import icu.groot.alan.hotel.service.AdminService;
import icu.groot.alan.hotel.service.HotelService;
import icu.groot.alan.hotel.service.OrderService;
import icu.groot.alan.hotel.service.RoomService;
import icu.groot.alan.hotel.util.BizException;
import icu.groot.alan.hotel.util.GrootApi;
import icu.groot.alan.hotel.util.ResultCodeEnum;
import icu.groot.alan.hotel.util.response.Result;
import icu.groot.alan.hotel.util.spring.BeanCopy;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.List;


/**
 * Admin
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Resource
    AdminService adminService;

    @Resource
    OrderService orderService;

    @Resource
    RoomService roomService;

    @Resource
    HotelService hotelService;

    @ApiOperation("Admin Login")
    @PostMapping("/login")
    public Result<LoginAdminVo> login(@RequestBody AdminLoginRo adminLoginRo, HttpServletResponse response){
        LoginAdminDto loginAdminDto = adminService.login(adminLoginRo.getAdminCode(), adminLoginRo.getAdminPassword());
        response.setHeader(GrootApi.Jwt.HEADER_ADMIN, loginAdminDto.getToken());
        LoginAdminVo loginAdminVo = new LoginAdminVo();
        BeanUtils.copyProperties(loginAdminDto, loginAdminVo);
        return Result.success(loginAdminVo);
    }

    @ApiOperation("Admin Get All Order")
    @PostMapping("/order")
    public Result<List<AdminOrderVo>> order(AdminOrderRo orderRo){
        System.out.println(orderRo.toString());
        List<OrderDo> informPhone = orderService.list(
                new QueryWrapper<OrderDo>()
                        .like("inform_phone", orderRo.getInformPhone())
                        .like("order_status", orderRo.getOrderStatus())
        );
        return Result.success(GrootApi.BeanCopy.convertListTo(informPhone, AdminOrderVo::new));
    }

    @ApiOperation("Admin Get All Room")
    @PostMapping({"/room"})
    public List<RoomVo> list(){
        return BeanCopy.convertListTo(
                roomService.list(),
                RoomVo::new
        );
    }

    @ApiOperation("Admin Update Room")
    @PostMapping({"/room/update"})
    public Result<String> update(@RequestBody RoomVo roomVo){
        RoomDo roomDo = new RoomDo();
        BeanUtils.copyProperties(roomVo, roomDo);
        roomDo.setRoomSpareNum(roomVo.getRoomNum());
        if (!roomService.updateById(roomDo)){
            throw new BizException(ResultCodeEnum.FAILED.setMessage("修改失败"));
        }
        return Result.success("修改成功", "");
    }

    @ApiOperation("Admin Add Room")
    @PostMapping({"/room/add"})
    public Result<String> add(@RequestBody RoomVo roomVo){
        RoomDo roomDo = new RoomDo();
        BeanUtils.copyProperties(roomVo, roomDo);
        roomDo.setVersion(0);
        roomDo.setCreateTime(LocalDateTime.now());
        roomDo.setRoomSpareNum(roomDo.getRoomNum());
        roomDo.setRoomImagesPath("http://localhost:40004/api/hotel/avatar-default.png");
        if (!roomService.save(roomDo)){
            throw new BizException(ResultCodeEnum.FAILED.setMessage("添加失败"));
        }
        return Result.success("添加成功", "");

    }
    @ApiOperation("Admin Update Room Disable")
    @PostMapping({"/room/disable/{roomCode}/{disable}"})
    public Result<String> disable(@PathVariable("roomCode") Integer roomCode, @PathVariable("disable") Boolean disable){

        if (!roomService.update(new UpdateWrapper<RoomDo>().eq("room_code", roomCode).set("disable", disable))){
            throw new BizException(ResultCodeEnum.FAILED.setMessage("修改失败"));
        }
        return Result.success("修改成功", "");

    }

    @ApiOperation("Admin Get Order Reverse")
    @PostMapping("/order/list/reverse/{phone}")
    public List<OrderListVo> listByReverse(@PathVariable("phone") String phone){
        if (phone == null || phone.trim().equals("null")){
            phone = "";
        }

        List<OrderDo> list = orderService.list(new QueryWrapper<OrderDo>()
                .in("order_status", OrderStatusEnum.REVERSE.getStatus(), OrderStatusEnum.OCCUPANCY.getStatus())
                .like("inform_phone", phone));
        return GrootApi.BeanCopy.convertListTo(list, OrderListVo::new);
    }

    @ApiOperation("Admin update Order Reverse")
    @PostMapping("/order/update/reverse/{orderCode}")
    public Result<String> updateByReverse(@PathVariable(value = "orderCode") String orderCode){
        if (!orderService.update(new UpdateWrapper<OrderDo>().eq("order_code", orderCode).set("order_status", OrderStatusEnum.OCCUPANCY.getStatus()))) {
            throw new BizException(ResultCodeEnum.FAILED.setMessage("操作失败"));
        }
        return Result.success("操作成功", "");
    }

    @ApiOperation("Admin update Room Refund")
    @PostMapping("/room/update/refund/{orderCode}")
    public Result<String> updateByRefund(@PathVariable(value = "orderCode") String orderCode){
        if (!orderService.update(new UpdateWrapper<OrderDo>().eq("order_code", orderCode).set("order_status", OrderStatusEnum.FINISH.getStatus()))) {
            throw new BizException(ResultCodeEnum.FAILED.setMessage("操作失败"));
        }
        return Result.success("操作成功", "");
    }

    @ApiOperation("Admin Update Hotel Info")
    @PostMapping("/hotel/update/info")
    public Result<String> updateHotel(@RequestBody HotelDo hotelDo){
        if (!hotelService.updateById(hotelDo)) {
            throw new BizException(ResultCodeEnum.FAILED.setMessage("修改失败"));
        }
        return Result.success("修改成功", "");
    }

    @ApiOperation("Admin Update password")
    @PostMapping("/update/password")
    public Result<String> updatePassword(@RequestBody AdminUpdatePasswordRo adminUpdatePasswordRo, HttpServletRequest request){
        if (
                adminUpdatePasswordRo.getAdminPassword() == null || adminUpdatePasswordRo.getAdminPassword().trim().equals("") ||
                adminUpdatePasswordRo.getAdminNewPassword() == null || adminUpdatePasswordRo.getAdminNewPassword().trim().equals("") ||
                adminUpdatePasswordRo.getAdminAgainNewPassword() == null || adminUpdatePasswordRo.getAdminAgainNewPassword().trim().equals("")
        ){
            throw new BizException(ResultCodeEnum.FAILED.setMessage("参数不全"));
        }

        if (!adminUpdatePasswordRo.getAdminNewPassword().equals(adminUpdatePasswordRo.getAdminAgainNewPassword())){
            throw new BizException(ResultCodeEnum.FAILED.setMessage("两次新密码不一样"));
        }

        AdminDo adminDoToken = new Gson().fromJson(request.getAttribute(GrootApi.Jwt.HEADER_ADMIN).toString(), AdminDo.class);
        AdminDo adminCode = adminService.getOne(new QueryWrapper<AdminDo>().eq("admin_code", adminDoToken.getAdminCode()));
        if (!adminCode.getAdminPassword().equals(adminUpdatePasswordRo.getAdminPassword())){
            throw new BizException(ResultCodeEnum.FAILED.setMessage("旧密码错误"));
        }

        adminCode.setAdminPassword(adminUpdatePasswordRo.getAdminAgainNewPassword());
        if (!adminService.updateById(adminCode)) {
            throw new BizException(ResultCodeEnum.FAILED.setMessage("修改失败"));
        }
        return Result.success("修改成功", "");
    }

    @ApiOperation("Admin Get Hotel Info")
    @PostMapping("/hotel/info")
    public Result<HotelDo> info(){
        return Result.success(hotelService.list().get(0));
    }


}
